<template>
  <div>
    <el-dialog class="pick-dialog" title="选择卡位" append-to-body :visible.sync="dialogVisible" :close-on-click-modal="false" width="800px" top="30vh">

      <div class="" v-loading="loading">
        <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form-new" label-width="68px">
          <el-form-item label="类型" prop="num">
            <b v-if="queryParams.zulinType==1">我的卡位</b>
            <b v-if="queryParams.zulinType==2">共享的卡位</b>
          </el-form-item>
          <el-form-item label="手机号" prop="tel">
            <el-input v-model="queryParams.tel" placeholder="请输入手机号" clearable size="small" />
          </el-form-item>
          <!-- <el-form-item label="编号" prop="num">
            <el-input v-model="queryParams.num" placeholder="请输入编号" clearable size="small" />
          </el-form-item> -->
          <el-form-item class="btns">
            <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            <el-button type="warning" icon="el-icon-search" @click="opendaoru">导入</el-button>
          </el-form-item>
        </el-form>
        <el-table ref="table"  :row-key="getRowKeys" @selection-change="handleSelectionChange" border :data="tableData.records" highlight-current-row height="500px" style="width: 100%">
          <!-- <el-table-column prop="num" label="编号" width="140"></el-table-column> -->
          <!-- <el-table-column prop="num" label="卡位类型" width="120">
            <template slot-scope="scope">
              <el-tag v-if="queryParams.zulinType==1" :type="commonMaps.telDeviceType[scope.row.deviceType||1].type">{{commonMaps.telDeviceType[scope.row.deviceType||1].label}}</el-tag>
              <el-tag v-if="queryParams.zulinType==2" :type="commonMaps.telDeviceType[2].type">{{commonMaps.telDeviceType[2].label}}</el-tag>
            </template>
          </el-table-column> -->
          <el-table-column :reserve-selection="true" type="selection" width="55">
          </el-table-column>
          <el-table-column prop="chuzufangName" label="管理人" width="100">
            <template slot-scope="scope">
              <span v-if="queryParams.zulinType==1">{{ scope.row.custodian }}</span>
              <span v-if="queryParams.zulinType==2">{{ scope.row.chuzufangName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="tel" label="手机号" width="150"></el-table-column>
          <el-table-column prop="carrierType" label="运营商" >
            <template slot-scope="scope">
              <div  v-if="scope.row.carrierType">
                <template v-if="carrierTypes&&carrierTypes[1]">
                  <span :key="scope.row.id" >
                    {{carrierTypes[scope.row.carrierType].name}}
                  </span>
                </template>
              </div>
              <div v-else>全部</div>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="设备状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.deviceStatus==1" type="success">在线</el-tag>
              <el-tag v-if="scope.row.deviceStatus==2" type="danger">离线</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="remark" label="备注">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top-start">
                <div class="zdy-des">{{ scope.row.remark }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div class="pages-box">
          <el-pagination @current-change="pageChange" :current-page="queryParams.pageNum" :page-sizes="[10, 20, 30, 40, 50, 60]" :page-size="queryParams.pageSize" layout="total, prev, pager, next, jumper" :total="tableData.total"></el-pagination>
        </div> -->
        <div class="center">
          <el-button @click="close('ruleForm')">取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
        </div>
      </div>
    </el-dialog>
    <!--批量 导入弹出 -->
    <el-dialog title="批量导入" :visible.sync="showInportVisible" width="430px" append-to-body>
      <div v-loading="isUploading" element-loading-text="正在处理中，可能时间较长，请耐心等待...">
        <el-upload ref="upload" :file-list="fileList" :limit="1" accept=".xlsx, .xls" :on-change="getFile" action="#" :disabled="isUploading" :auto-upload="false" drag style="margin-bottom: 15px">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip text-center" slot="tip">
            <!-- <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div> -->
            <span>仅允许导入xls、xlsx格式文件。</span>
            <div>导入的手机号如果在列表中，会自动选中，不在列表中的手机号会忽略。</div>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline;margin:10px 0" @click="downloadModel">下载模板</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showInportVisible = false">取 消</el-button>
          <el-button type="primary" @click="daoruSure" :loading="isUploading">确 定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import phoneApi from "@/api/phoneManage";
import XLSX from "xlsx";
export default {
  name: "selectKawei",
  data() {
    return {
      showInportVisible: false,
      isUploading: false,
      fileList:[],
      activeName: "0",
      listOne: [],
      dialogVisiblese: false,
      dialogVisible: false,
      names: "",
      xilie: [],
      loading: false,
      tableData: {
        records: [],
        total: 0,
      },
      queryParams: {
        zulinType: 2,
        status: 1,
      },
      multipleSelection: [],
      oldRows: [],
      telArr:[]
    };
  },
  created() {},
  computed: {
    carrierTypes() {
      return this.arrayToObject(this.$store.getters.gameYunyingshangList, "id");
    },
  },
  methods: {
    getRowKeys(row) {
      if(this.zulinType == 2){
        return row.telManageId
      }else{
        return row.id
      }
   },
    // 选择项改变
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 改变某一行
    selectRow(selection, row){
      // console.log("%c Line:144 🍤 row", "color:#6ec1c2", row);

    },

    open(zulinType = 2, rows) {
      this.dialogVisible = true;
      this.queryParams.zulinType = zulinType;
      this.getList();
      if (rows && rows.length) {
        this.oldRows = rows;
      }
    },

    // 改变类
    zulinTypeChange(e) {
      // this.queryParams.pageNum = 1;
      this.getList();
    },
    // 打开导入
    opendaoru() {
      this.fileList = []
      this.telArr = []
      this.showInportVisible = true;
    },
    // 下载模板
    downloadModel() {
      window.open('https://imgage.maimaihao.com/yuduhulian/%E5%88%86%E4%BA%AB%E7%9F%AD%E4%BF%A1%E5%AF%BC%E5%85%A5%E5%8F%B7%E7%A0%81%E6%A8%A1%E6%9D%BF.xlsx')
    },
    // 获取文件
    async getFile(file) {
      const jsonStr = await this.file2Xce(file);
      if (jsonStr && jsonStr.length) {
        const telList = jsonStr[0].sheet;
        if (telList && telList.length) {
          const telArr = [];
          telList.forEach((t) => {
            telArr.push(String(t["手机号"]));
          });
          // telArr
          this.telArr = telArr
        } else {
          return this.$message.error("没有获取到手机号！");
        }
      } else {
        return this.$message.error("没有获取到手机号！");
      }
    },
    // 解析文件
    async file2Xce(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        reader.onload = function (e) {
          const data = e.target.result;
          this.wb = XLSX.read(data, {
            type: "binary",
          });
          const result = [];
          this.wb.SheetNames.forEach((sheetName) => {
            result.push({
              sheetName: sheetName,
              // 调用：sheet_to_json 方法，将文件内容解析成 json 格式
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName]),
            });
          });
          resolve(result);
        };
        debugger;
        reader.readAsBinaryString(file.raw);
      });
    },
    // 确认导入
    daoruSure() {
      if (this.telArr && this.telArr.length) {
        this.tableData.records.forEach((r) => {
          if (this.telArr.includes(r.tel)) {
            this.$refs.table.toggleRowSelection(r,true);
          }
        });
      }else{
        return this.$message.error("没有获取到手机号！");
      }
      this.showInportVisible = false;
    },
    // 获取列表
    getList() {
      this.loading = true;
      if (this.queryParams.zulinType == 1) {
        this.queryParams.carrierType = "";
        this.queryParams.zulinEnable = "";
        this.queryParams.chuzufangEnable = "";
        this.queryParams.isLease = 1;
        this.queryParams.deviceType = 2;
        phoneApi.getAllList(this.queryParams).then((response) => {
          this.tableData.records = response.data;
          this.loading = false;
          this.showOldSelect();
        });
      } else {
        // 租赁的列表
        this.queryParams.carrierType = "";
        this.queryParams.zulinEnable = 1;
        this.queryParams.chuzufangEnable = 1;
        phoneApi.telLeaseDetailslist(this.queryParams).then((response) => {
          this.tableData.records = response.rows;
          this.tableData.total = response.total;
          this.loading = false;
          this.showOldSelect();
        });
      }
    },
    // 回显已勾选
    showOldSelect() {
      this.$nextTick(() => {
        if (this.oldRows && this.oldRows.length) {
          // 回显已勾选
          const oldRowIds = this.oldRows.map((obj) => {
            return obj.tel;
          });
          this.tableData.records.forEach((r) => {
            if (oldRowIds.includes(r.tel)) {
              this.$refs.table.toggleRowSelection(r,true);
            }
          });
        }
      });
    },

    // 搜索
    search() {
      // this.queryParams.pageNum = 1;
      // this.queryParams.pageSize = 10;
      this.getList();
    },

    submitForm() {
      if (this.multipleSelection.length == 0) {
        return this.$alert("请选择一条记录！");
      }
      this.$emit("change", JSON.parse(JSON.stringify(this.multipleSelection)));
      this.close();
    },
    close() {
      this.$refs.table.clearSelection()
      this.multipleSelection = [];
      this.tableData.records = [];
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
.tip {
  color: red;
}
.twos {
  width: 100%;
  padding: 11px 20px;
  border: 1px solid #f2f2f2;
}
.bangding-box {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  .bditem {
    margin-right: 20px;
    cursor: pointer;
    color: $primary;
    &:last-child {
      margin-right: 0;
    }
  }
}
</style>
